import ast
import re

from ai.models import Article, ArticleCategory, ArticleKeyword


def find_or_create_keywords(keyword):
    res = ArticleKeyword.objects.filter(text__exact=keyword)
    if len(res):
        return res[0].id
    else:
        instance = ArticleKeyword.objects.create(text=keyword)
        return instance.id


def find_or_create_category(category_name):
    res = ArticleCategory.objects.filter(name=category_name)

    if len(res):
        return res[0]
    else:
        instance = ArticleCategory.objects.create(name=category_name)
        return instance


def convert_keyword_list(original_list):
    keywords = ast.literal_eval(original_list)
    return keywords


def get_keywords_id(keywords_str):
    keywords = convert_keyword_list(keywords_str)
    foreign_keys = []
    for keyword in keywords:
        foreign_keys.append(find_or_create_keywords(keyword))
    return foreign_keys


def parse_category(categories_str, article):
    first_category = find_or_create_category(categories_str)
    article.category.add(first_category)


def merge_category_articles_by_name(target_category_name, source_category_name):
    """
    合并两个分类下的文章, 比如传递 target_category_name="经济" source_category_name="商业"，
    将商业分类下的文章合并到经济分类下，且更新 category_raw 字段为 "经济"
    最后将商业分类删除
    :param target_category_name:
    :param source_category_name:
    :return:
    """
    target_category = ArticleCategory.objects.filter(name=target_category_name).first()
    source_category = ArticleCategory.objects.filter(name=source_category_name).first()

    if source_category is None or target_category is None:
        return

    source_category_articles = Article.objects.filter(category=source_category)

    for article in source_category_articles:
        # article.categories.add(target_category)
        # 文章分类设置为 target_category
        article.category.clear()
        article.category.add(target_category)
        article.categories_raw = target_category.name
        article.save()
    source_category.delete()